import { messageError } from '@/hooks'

// 修改css变量
export function setCssVar(prop: string, color: string, dom = document.documentElement) {
	if (!color) {
		messageError({ message: '颜色取值不能为空！' })
		return
	}
	dom.style.setProperty(prop, color)
}

// 批量主题色css,及其css衍生色
export function batchCssVar(pre: string, color: string, dom = document.documentElement) {
	if (!color) {
		messageError({ message: '颜色取值不能为空！' })
		return
	}
	setCssVar(pre, color, dom)
	const mixBlack = '#000000'
	const mixWhite = '#ffffff'
	for (let i = 1; i < 10; i += 1) {
		if (i !== 1 && i !== 4 && i !== 6) {
			setCssVar(`${pre}-${i === 2 ? 'dark' : 'light'}-${i}`, mix(color, i === 2 ? mixBlack : mixWhite, i * 0.1), dom)
		}
	}
}

// 计算颜色
export function mix(color1: string, color2: string, weight: number) {
	weight = Math.max(Math.min(Number(weight), 1), 0)
	const r1 = parseInt(color1.substring(1, 3), 16)
	const g1 = parseInt(color1.substring(3, 5), 16)
	const b1 = parseInt(color1.substring(5, 7), 16)
	const r2 = parseInt(color2.substring(1, 3), 16)
	const g2 = parseInt(color2.substring(3, 5), 16)
	const b2 = parseInt(color2.substring(5, 7), 16)
	const r = Math.round(r1 * (1 - weight) + r2 * weight)
	const g = Math.round(g1 * (1 - weight) + g2 * weight)
	const b = Math.round(b1 * (1 - weight) + b2 * weight)
	const _r = ('0' + (r || 0).toString(16)).slice(-2)
	const _g = ('0' + (g || 0).toString(16)).slice(-2)
	const _b = ('0' + (b || 0).toString(16)).slice(-2)
	return '#' + _r + _g + _b
}
